import React, { Component, Fragment } from 'react';
import { Link } from 'dva/router';
import { connect } from 'dva';
import { Spin, message, Button, Card, Alert, Form, Input, InputNumber, Upload, Icon, Row, Col, Table, Checkbox } from 'antd';
import InputMy from '@/components/Input/index'
import router from 'umi/router';
import styles from './index.less';
import FromTable from './FromTable'

const namespace = 'expresssetting';
@Form.create()
class EditTemp extends Component {
    obj = {
        FirstFee: -1,
        FirstAmount: -1,
        AdditionalFee: -1,
        AdditionalAmount: -1,
    }
    constructor(props) {
        super(props);

        this.state = {
        };
    }

    componentWillMount() {
        this.GetInfo();
        window.Isoption = false;
    }

      componentDidMount() {
        window.Isoption = true;
      }
    GetInfo = () => {
        const { dispatch, match, form } = this.props;
        let tempId = match.params.id;

        dispatch({
            type: `${namespace}/GetFreightTemplate`,
            param: { id: tempId, p: Math.random() },
            callback: (data) => {

                this.obj = {
                    FirstFee: data.FirstFee,
                    AdditionalFee: data.AdditionalFee,
                    FirstAmount: data.FirstAmount,
                    AdditionalAmount: data.AdditionalAmount,
                }
                let dataMap = []
                console.log(this.obj)
                data.ValuationRules && data.ValuationRules.forEach((value, index) => {
                    if (!value.id) {
                        value = { ...value, id: Date.now() + index, disabled: true }
                    }
                    dataMap.push(value);
                });

                form.setFieldsValue({
                    DefualtFree: { ...this.obj },
                    ValuationRules: dataMap
                });
                // console.log(this.props.form.getFieldValue('DefualtFree'))
            }
        });
    };

    onChangeDefualtFree = (name, e) => {
        const { form } = this.props;
        this.obj[name] = e;
        form.setFieldsValue({
            DefualtFree: { ...this.obj },
        });

    }

    compareToDefualtFree = (rule, value, callback) => {
        const form = this.props.form;

        // if (!this.obj.AdditionalFee || !this.obj.AdditionalAmount || !this.obj.FirstFee || !this.obj.FirstAmount) {
        //     callback('请设置默认运费');
        // } else if (!/^[1-9]\d*$/.test(this.obj.FirstAmount) || !/^[1-9]\d*$/.test(this.obj.AdditionalAmount)) {
        //     callback('件数请输入正整数');

        // } else if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.obj.FirstFee) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(this.obj.AdditionalFee)) {
        //     callback('请输入正确的金额');

        // } else {
        //     callback()
        // }
        if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
            callback('默认运费必须填写');
        } else {
            callback()
        }
    }

    handleSubmit = () => {
        let { dispatch, match } = this.props;
        let tempId = match.params.id;
        this.props.form.validateFields((err, values) => {
            if (!err) {

                values = { ...values, ...this.obj, Id: tempId }
                // if (!values.ValuationRules || values.ValuationRules.length < 1) {
                //     message.error('必须选择配送区域')
                //     return;
                // }
                dispatch({
                    type: `${namespace}/UpdateFreightTemplate`,
                    param: values,
                    callback: {
                        success: (data) => {
                            message.success("修改成功");
                            router.replace({
                                pathname: `/${window.storeId}/delivery/express`,
                            });
                        },
                        error: (data) => {
                            message.error("修改失败" + data.Msg);
                        }
                    }
                });
            }
        });
    };

    // 校验默认件数
    validateFirstAmount = (rule, value, callback) => {
        if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
            if (!/^[1-9]\d*$/.test(value) || !/^[1-9]\d*$/.test(value)) {
                callback('件数请输入正整数');
            } else {
                callback()
            }
        } else {
            if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
                callback()
            } else {
                callback('请输入件数');
            }
        }
    }

    //校验默认金额
    validateFirstFee = (rule, value, callback) => {
        if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
            if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value)) {
                callback('请输入正确的金额');

            } else if (0 > parseFloat(value) || parseFloat(value) > 9999) {
                callback('运费最大可输入9999元');
            } else {
                callback()
            }
        } else {
            if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
                callback()
            } else {
                callback('请输入金额');
            }
        }
    }

    // 校验增加的件数
    validateAdditionalAmount = (rule, value, callback) => {
        if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
            if (!/^[1-9]\d*$/.test(value) || !/^[1-9]\d*$/.test(value)) {
                callback('件数请输入正整数');
            } else {
                callback()
            }
        } else {
            if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
                callback()
            } else {
                callback('请输入件数');
            }
        }
    }

    //校验增加的金额
    validateAdditionalFee = (rule, value, callback) => {
        console.log("效验")
        if (this.obj.AdditionalFee != -1 || this.obj.AdditionalAmount != -1 || this.obj.FirstFee != -1 || this.obj.FirstAmount != -1) {
            if (!/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value) || !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(value)) {
                callback('请输入正确的金额');

            } else if (0 > parseFloat(value) || parseFloat(value) > 9999) {
                callback('运费最大可输入9999元');
            } else {
                callback()
            }
        } else {
            if (this.obj.AdditionalFee == -1 && this.obj.AdditionalAmount == -1 && this.obj.FirstFee == -1 && this.obj.FirstAmount == -1) {
                callback()
            } else {
                callback('请输入金额');
            }
        }
    }

    render() {
        const formItemLayout = {
            labelCol: {
                xs: { span: 4 },
                sm: { span: 4 },
                md: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 9 },
                sm: { span: 9 },
                md: { span: 9 },
            },
        };
        const defaultLayout = {
            labelCol: {
                xs: { span: 4 },
                sm: { span: 4 },
                md: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 19 },
                sm: { span: 19 },
                md: { span: 19 },
            },
        };


        const {
            getFieldDecorator,
            getFieldsError,
            getFieldError,
            isFieldTouched,
            getFieldValue,

        } = this.props.form;
        const {
            loading,
            loadbtn,
            expresssetting: { freightTemplateInfo }
        } = this.props;

        return (
            <Fragment>
                <Spin spinning={loading}>
                    <Card bordered={false} className={styles.AddTemplate}>
                        <Form >
                            <Row>
                                <Col>
                                    <Form.Item
                                        {...formItemLayout}
                                        label="模板名称"
                                    >
                                        {getFieldDecorator('Name', {
                                            rules: [{ required: true, message: '模板名称必须填写' }],
                                            initialValue: freightTemplateInfo && freightTemplateInfo.Name,
                                        })(
                                            <InputMy maxLength={20} showtotal />
                                        )}

                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col>
                                    <Form.Item
                                        label={<span className={'ant-form-item-required'}>默认运费</span>}
                                        labelCol={{ span: 4 }}
                                        wrapperCol={{ span: 20 }}
                                    >
                                        {getFieldDecorator('DefualtFree', {
                                            validateTrigger: 'onBlur',
                                            rules: [{ validator: this.compareToDefualtFree, }],
                                        })(
                                            <div>
                                                <Row>
                                                    <Col span={4}>
                                                        <Form.Item
                                                            className={styles.innerFormItem}
                                                        >
                                                            {
                                                                getFieldDecorator('FirstAmount', {
                                                                    initialValue: this.obj.FirstAmount,
                                                                    validateTrigger: 'onBlur',
                                                                    rules: [{ validator: this.validateFirstAmount, }
                                                                    ],
                                                                })(
                                                                    <InputMy
                                                                        maxLength={4}
                                                                        addonAfter="件"
                                                                        onChange={(e) => this.onChangeDefualtFree('FirstAmount', e.target.value)}
                                                                        style={{ width: '100%' }}
                                                                    />
                                                                )
                                                            }
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={1} >
                                                        <span className='Text'>&nbsp;内，</span>
                                                    </Col>
                                                    <Col span={4}>
                                                        <Form.Item
                                                            className={styles.innerFormItem}
                                                        >
                                                            {
                                                                getFieldDecorator('FirstFee', {
                                                                    initialValue: this.obj.FirstFee ? this.obj.FirstFee : "0",
                                                                    validateTrigger: 'onBlur',
                                                                    rules: [{ validator: this.validateFirstFee, }
                                                                    ],
                                                                })(
                                                                    <InputMy
                                                                        addonAfter="元"
                                                                        maxLength={7}
                                                                        onChange={(e) => this.onChangeDefualtFree('FirstFee', e.target.value)}
                                                                        style={{ width: '100%' }}
                                                                    />
                                                                )
                                                            }
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={2} style={{ width: '5em' }}>
                                                        <span className='Text'>；每增加</span>
                                                    </Col>
                                                    <Col span={4}>
                                                        <Form.Item
                                                            className={styles.innerFormItem}
                                                        >
                                                            {
                                                                getFieldDecorator('AdditionalAmount', {
                                                                    initialValue: this.obj.AdditionalAmount,
                                                                    validateTrigger: 'onBlur',
                                                                    rules: [{ validator: this.validateAdditionalAmount, }
                                                                    ],
                                                                })(
                                                                    <InputMy
                                                                        addonAfter="件"
                                                                        maxLength={4}
                                                                        onChange={(e) => this.onChangeDefualtFree('AdditionalAmount', e.target.value)}
                                                                        style={{ width: '100%' }}
                                                                    />
                                                                )
                                                            }
                                                        </Form.Item>
                                                    </Col>
                                                    <Col span={2} style={{ width: '5em' }}>
                                                        <span className='Text'>&nbsp;增加运费</span>
                                                    </Col>
                                                    <Col span={4}>
                                                        <Form.Item
                                                            className={styles.innerFormItem}
                                                        >
                                                            {
                                                                getFieldDecorator('AdditionalFee', {
                                                                    initialValue: this.obj.AdditionalFee ? this.obj.AdditionalFee : "0",
                                                                    validateTrigger: 'onBlur',
                                                                    rules: [{ validator: this.validateAdditionalFee, }
                                                                    ],
                                                                })(
                                                                    <InputMy
                                                                        addonAfter="元"
                                                                        maxLength={7}
                                                                        onChange={(e) => this.onChangeDefualtFree('AdditionalFee', e.target.value)}
                                                                        style={{ width: '100%' }}
                                                                    />
                                                                )
                                                            }
                                                        </Form.Item>
                                                    </Col>
                                                </Row>
                                            </div>
                                        )}
                                    </Form.Item>
                                </Col>

                            </Row>
                            <Row>
                                <Col>
                                    <Form.Item
                                        {...defaultLayout}
                                        label="指定配送区域"
                                    >
                                        {getFieldDecorator('ValuationRules', {
                                            rules: [],
                                            //initialValue: freightTemplateInfo && freightTemplateInfo.ValuationRules,
                                        })(
                                            <FromTable
                                                form={this.props.form}
                                            //value={ freightTemplateInfo && freightTemplateInfo.ValuationRules}
                                            />
                                        )}

                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={19} offset={4}>
                                    {getFieldDecorator('IsDefault', {
                                        //rules: [{ required: true }],
                                        valuePropName: 'checked',
                                        initialValue: freightTemplateInfo && freightTemplateInfo.IsDefault,
                                    })(
                                        <Checkbox  >设为新商品默认模板（新添加的商品支持商家配送时的默认模板）</Checkbox>
                                    )}
                                </Col>
                            </Row>
                            <Row>
                                <Col span={3} offset={4}>
                                    <Button type="primary" onClick={this.handleSubmit} loading={loadbtn}>
                                        保存
                </Button>
                                </Col>
                            </Row>
                        </Form>

                    </Card>
                </Spin>
            </Fragment>
        );
    }
}
export default connect(({ expresssetting, global, loading }) => ({
    expresssetting,
    oemInfo: global.oemInfo,
    loadbtn: loading.effects['expresssetting/UpdateFreightTemplate'],
    loading: loading.effects['expresssetting/GetFreightTemplate'],
}))(EditTemp);
